package com.wangshb.agent.study.bytebuddy.methoddelegation;

import com.wangshb.agent.study.bytebuddy.HelloWolrd;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import net.bytebuddy.matcher.ElementMatchers;

import java.util.function.Function;

import static net.bytebuddy.matcher.ElementMatchers.named;

public class CustomInterceptor {

    // 方法签名随意, 但是不能定义多个方法，不然会报错的
    public static String test(Object argument) {
        return "Hello from " + argument;
    }


    public static void main(String[] args) throws Exception {

        Class<? extends Function> say = new ByteBuddy()
                // 指定父类
                .subclass(Function.class)
                // 指定Function类的apply方法, 或者ElementMatchers.named("apply")
                .method(named("apply"))
                // 拦截方法调用，返回固定值
                .intercept(MethodDelegation.to(CustomInterceptor.class))
                // 产生字节码
                .make()
                .load(CustomInterceptor.class.getClassLoader())
                // 获取class对象
                .getLoaded();


        System.out.println(say.newInstance().apply("Byte Buddy"));
    }
}
